import React, { useState, useEffect, useMemo } from "react";
import "../../assets/style/Home/index.scss";
import {
  Layout,
  Space,
  Button,
  Modal,
  Form,
  message,
  Table,
  Select,
  Descriptions,
  Image as MyImage,
  List,
  Rate,
  Popconfirm,
} from "antd";

import {
  getStudentByClass,
  getStudentList,
} from "../../service/student.service";
import ReportService from "../../service/report.service";

import domtoimage from "dom-to-image";
import { useAuth } from "../../context/auth-context";
import { base64toFile } from "../../utils";

const { Content } = Layout;

const Home = () => {
  const { user } = useAuth();
  const [modal, contextHolder] = Modal.useModal();

  const [examOptions, setExamOptions] = useState([]);
  const [stuOptions, setStuOptions] = useState([]);
  const [report, setReport] = useState([]);
  const [stuId, setStuId] = useState(user.type === "student" ? user.id : 0);
  const [dataSource, setDataSource] = useState(null);
  const [open, setOpen] = useState(false);
  const [reportOpen, setReportOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);

  const [form] = Form.useForm();

  const submitReportModal = () => {
    setOpen(false);
  };

  const cancelReportModal = () => {
    setReportOpen(false);
  };

  // 生成错题报告
  const newErrorReport = (values) => {
    setConfirmLoading(true);
    if (!values.stuid) {
      values.stuid = stuId;
    }
    ReportService.outputReport(values)
      .then((res) => {
        getReportList();
        setOpen(false);
        setConfirmLoading(false);
        watchReport(res, true);
      })
      .catch((err) => {
        message.warning(err);
        setConfirmLoading(false);
      });
  };

  const watchReport = (values, isUpload = false) => {
    if (values.id !== undefined) setStuId(values.id);
    const data = values.studentUseReport ? values.studentUseReport : values;
    setReport(data);
    setReportOpen(true);
    if (isUpload) getImg(values.examId);
  };

  const newErrorReportFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };

  const openOutputReport = () => {
    setOpen(true);
  };

  const getImg = (examId) => {
    const node = document.getElementById("report");
    const style = window.getComputedStyle(node);
    const width = style.width.replace("px", "");
    const height = style.height.replace("px", "");
    domtoimage
      .toPng(node, {
        quality: 1,
        height,
        width,
        cacheBust: true,
        bgcolor: "white",
        proxy: "https://cors-anywhere.herokuapp.com/",
      })
      .then(async (defaultUrl) => {
        const img = new Image();
        img.src = defaultUrl;
        img.setAttribute("className", "pngImg"); // 方便设置样式
        const link = document.createElement("a");
        link.download = "错题报告.png";
        link.href = defaultUrl;
        link.click();
        const fileName = report?.name + report?.examName;
        const file = base64toFile(defaultUrl, fileName);
        await ReportService.uploadImage({
          file,
          stuid: stuId,
          examid: examId || report.examId,
        });
        message.success("导出成功！");
      })
      .catch((err) => {
        console.log(err);
        message.error("导出失败！原因" + err);
      });
  };

  // 初始化
  useEffect(() => {
    // 获取学生列表
    if (user.type === "teacher") {
      getStudentByClass(user.classId)
        .then((res) => {
          const data = res.studentList.map((v) => ({
            label: v.name,
            value: v.studentId,
          }));
          setStuOptions(data);
        })
        .catch((err) => {
          console.error(err);
        });
    } else if (user.type === "admin") {
      getStudentList(user.classId)
        .then((res) => {
          const data = res.studentList.map((v) => ({
            label: v.name,
            value: v.studentId,
          }));
          setStuOptions(data);
        })
        .catch((err) => {
          console.error(err);
        });
    }
    getReportList();
  }, []);

  const getAllExam = (stuId) => {
    // 获取所有考试场次
    ReportService.getAllExam(stuId)
      .then((res) => {
        const data = res.map((v) => ({
          label: v.name,
          value: v.id,
        }));
        setExamOptions(data);
      })
      .catch((err) => {
        console.log(err);
        setExamOptions([]);
      });
  };
  const getReportList = () => {
    // 获取错误报告列表
    if (user.type === "teacher") {
      ReportService.getReportListByClassId({ classId: user.classId })
        .then(setDataSource)
        .catch((err) => {
          console.log(err);
        });
    } else {
      const id = user.type === "admin" ? "" : stuId;
      ReportService.getAllReportsById({ stuId: id })
        .then(setDataSource)
        .catch((err) => {
          console.log(err);
        });
    }
  };

  const deleteReport = (stuid, examId) => {
    ReportService.deletereport(stuid, examId)
      .then(() => {
        message.success("删除成功！");
        getReportList();
      })
      .catch((err) => {
        console.log(err);
      });
  };

  const DeleteButton = (props) => {
    const { record } = props;
    const examid = record.studentUseReport
      ? record.studentUseReport.examId
      : record.examId;
    const id = record.id ? record.id : record.studentId;
    return (
      <Popconfirm
        title="警告"
        description="确定要删除吗？"
        onConfirm={() => deleteReport(id, examid)}
        okText="确定"
        cancelText="取消"
      >
        <Button danger>删除报告</Button>
      </Popconfirm>
    );
  };

  useEffect(() => {
    if (stuId) getAllExam(stuId);
  }, [stuId]);

  const columns = useMemo(() => {
    if (user.type === "student") {
      return [
        {
          title: "考试场次",
          dataIndex: "examName",
          key: "examName",
        },
        {
          title: "报告链接",
          dataIndex: "link",
          key: "link",
          render: (href) => {
            if (href)
              return (
                <a target="_blank" href={href} rel="noreferrer">
                  查看
                </a>
              );
            return <>暂无</>;
          },
        },
        {
          title: "操作",
          key: "action",
          render: (_, record) => (
            <Space size="middle">
              <Button onClick={() => watchReport(record)}>查看报告</Button>
              <DeleteButton record={record} />
            </Space>
          ),
        },
      ];
    } else {
      return [
        {
          title: "姓名",
          dataIndex: "name",
          key: "name",
        },
        {
          title: "考试场次",
          key: "examName",
          render: (_, record) =>
            record.studentUseReport
              ? record.studentUseReport.examName
              : record.examName,
        },
        {
          title: "报告链接",
          dataIndex: "link",
          key: "link",
          render: (href) => {
            if (href)
              return (
                <a target="_blank" href={href} rel="noreferrer">
                  查看
                </a>
              );
            return <>暂无</>;
          },
        },
        {
          title: "操作",
          key: "action",
          render: (_, record) => (
            <Space size="middle">
              <Button onClick={() => watchReport(record)}>查看报告</Button>
              <DeleteButton record={record} />
            </Space>
          ),
        },
      ];
    }
  }, [user.type]);
  return (
    <div className="analyze">
      <Space
        direction="vertical"
        style={{
          width: "100%",
        }}
        size={[0, 48]}
      >
        <Layout>
          <Content>
            <div className="operation_line">
              <Space size="middle">
                <Button type="primary" onClick={openOutputReport}>
                  生成错题报告
                </Button>
              </Space>
            </div>
            <Table
              columns={columns}
              dataSource={dataSource}
              pagination={{ defaultPageSize: 10 }}
            />
          </Content>
        </Layout>
      </Space>
      <div className="Modal_container">
        {/* 生成错题报告 */}
        <Modal
          title="生成错题报告"
          open={open}
          onOk={submitReportModal}
          onCancel={submitReportModal}
          okText="确认"
          cancelText="取消"
          footer={null}
        >
          <Form
            name="basic"
            form={form}
            labelCol={{
              span: 8,
            }}
            wrapperCol={{
              span: 16,
            }}
            style={{
              maxWidth: 600,
            }}
            initialValues={{
              remember: true,
            }}
            onFinish={newErrorReport}
            onFinishFailed={newErrorReportFailed}
            autoComplete="off"
          >
            {user && user.type !== "student" ? (
              <Form.Item label="学生" name="stuid">
                <Select
                  style={{ width: 100 }}
                  onChange={setStuId}
                  options={stuOptions}
                />
              </Form.Item>
            ) : (
              <></>
            )}

            <Form.Item label="考试场次" name="paperid">
              <Select style={{ width: 100 }} options={examOptions} />
            </Form.Item>

            <Form.Item
              wrapperCol={{
                offset: 8,
                span: 16,
              }}
            >
              <Button type="primary" htmlType="submit" loading={confirmLoading}>
                确定
              </Button>
            </Form.Item>
          </Form>
        </Modal>

        <Modal
          open={reportOpen}
          onCancel={cancelReportModal}
          okText="确认"
          cancelText="取消"
          width={"80%"}
          footer={null}
        >
          <div id="report">
            <p
              style={{
                width: "100%",
                display: "flex",
                justifyContent: "center",
                fontSize: 18,
                fontWeight: "bold",
              }}
            >
              错题报告
            </p>
            <Descriptions>
              <Descriptions.Item label="姓名">{report?.name}</Descriptions.Item>
              <Descriptions.Item label="考试场次">
                {report?.examName}
              </Descriptions.Item>
            </Descriptions>
            <span style={{ fontSize: 14, fontWeight: "bold" }}>错题列表</span>
            <List
              itemLayout="vertical"
              size="large"
              dataSource={report?.list}
              renderItem={(item, idx) => {
                const { answer, difficulty, knowledge, question } = item;
                return (
                  <List.Item
                    key={`des-${answer}-${knowledge}-${question.content}`}
                  >
                    {question?.type === "picture" ? (
                      <>
                        <MyImage
                          width="100%"
                          height="50vh"
                          style={{ objectFit: "contain" }}
                          src={question?.content}
                        />
                        <MyImage
                          width="100%"
                          height="50vh"
                          style={{ objectFit: "contain" }}
                          src={answer}
                        />
                      </>
                    ) : (
                      <>
                        <p>{question.content}</p>
                        <p>答案：{answer}</p>
                      </>
                    )}
                    <p
                      style={{
                        width: "100%",
                        display: "flex",
                        justifyContent: "space-between",
                      }}
                    >
                      <span>知识点：{knowledge}</span>
                      <Rate disabled count={3} defaultValue={difficulty} />
                    </p>
                  </List.Item>
                );
              }}
            />
          </div>
          <Button onClick={() => getImg(report?.examId)}>保存</Button>
        </Modal>
      </div>
      {contextHolder}
    </div>
  );
};

export default Home;
